package com.xxx.server.controller;


import com.alibaba.fastjson.JSONObject;
import com.xxx.server.pojo.Admin;
import com.xxx.server.pojo.request.AdminLoginParam;
import com.xxx.server.pojo.response.RespBean;
import com.xxx.server.service.IAdminService;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * <p>
 *  登录控制
 * </p>
 *
 * @author cd
 * @since 2023-11-12
 */
@RestController
public class AdminController {
    @Resource
    private IAdminService iAdminService;
    @PostMapping("/login")
    @ApiOperation("登录")
    public RespBean login(@RequestBody AdminLoginParam adminLoginParam, HttpServletRequest request){
        return iAdminService.login(adminLoginParam.getUsername(),adminLoginParam.getPassword(),adminLoginParam.getCode(),request);
    }

    @ApiOperation("获取登录信息")
    @PostMapping("/admin/info")
    public Admin getLoginInfo(Principal principal){
        if (principal == null){
            return null;
        }
        String name = principal.getName();
        Admin admin = iAdminService.getAdminByUserName(name);
        admin.setPassword(null);
        admin.setRoles(iAdminService.getRoles(admin.getId()));
        return admin;
    }
    @PostMapping("/logout")
    @ApiOperation("退出")
    public RespBean logout(Principal principal){
        SecurityContextHolder.clearContext();
        return RespBean.success("退出登录成功");
    }

}
